package test;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.chaoyi.dao.mysql.AppointmentMapper;
import com.chaoyi.dao.mysql.BarrageAndUserMapper;
import com.chaoyi.dao.mysql.FictionMapper;
import com.chaoyi.dao.mysql.HomeMapper;
import com.chaoyi.dao.mysql.PortraitPicturesMapper;
import com.chaoyi.dao.mysql.PortraitVideoMapper;
import com.chaoyi.dao.mysql.PrivatePlayMapper;
import com.chaoyi.dao.mysql.WhiteHomeMapper;
import com.chaoyi.model.Appointment;
import com.chaoyi.model.BarrageAndUser;
import com.chaoyi.model.Fiction;
import com.chaoyi.model.Home;
import com.chaoyi.model.PortraitPictures;
import com.chaoyi.model.PortraitPicturesSet;
import com.chaoyi.model.PortraitVideo;
import com.chaoyi.model.PrivatePlay;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

public class ImgMove {

	// public static void main(String[] args) {
	// // 上传方法（地址、文件名、个数）
	// //
	// 地址：http://cy001.b0.upaiyun.com/sp001/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png
	// String path =
	// "http://101.95.48.97:8005/res/upload/interface/apptutorials/manualstypeico/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png";
	// String[] pathArray = path.split("/");
	// String value = pathArray[pathArray.length - 1];
	// UpYunUtil.upLoad("F:/ImgMove/6f83ce8f-0da5-49b3-bac8-fd5fc67d2725.png",
	// value, 1);
	// }
	public static String errorLog ="";

	public static void main(String[] args) {
		// 拿到要下载的图片地址
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		WhiteHomeMapper entityMapper = context.getBean(WhiteHomeMapper.class);
		List<Home> urlList = entityMapper.findList(0+"",1000000+"","");
		
		for (int i = 0; i < urlList.size(); i++) {
			if(urlList.get(i).getVideoId()>= 0){
				// 下载图片参数
				// 下载网络地址
				String urlStr = urlList.get(i).getImgUrl();
				if( urlStr==null || urlStr.equals("")){
					System.out.println("id:"+urlList.get(i).getVideoId()+" Url为空，跳过");
					continue;
				}
			    //  http://cy001.b0.upaiyun.com/comment/img/280e5d2a8c66468aa0e79a1f17092dc6.jpg
				String urlSplit = StringSplit(urlStr);
				String[] urlStrArray = urlSplit.split("/");
				// 下载到本地文件名
				String fileName = urlStrArray[urlStrArray.length - 1];
				// 保存到本地地址
				String savePath = "F:/updownImg";
				try {
					// 下载方法
					downLoadFromUrl(urlStr, fileName, savePath);
					// 上传方法
//					File file = new File("F:/updownImg/"+fileName);
//					// “/comment/img/280e5d2a8c66468aa0e79a1f17092dc6.jpg” 去掉第一个“/”
					String str = urlSplit.substring(1, urlSplit.length());
					uploadFile("F:/updownImg/"+fileName,str);
//					String updateUrl = ApkOSSManageUtil.uploadFile(new ApkOSSConfigure(), file,str);
//					System.out.println("上传地址：" + updateUrl);
					Home entity = urlList.get(i);
					entity.setImgUrl("http://mtp.myche51.cn/"+str);
					//更新url字段
					int k = entityMapper.alertHomeSave(entity);
					if(k==1){
						System.out.println("更新表数据成功，id="+entity.getVideoId());
					}else{
						System.out.println("更新数据失败！！id="+entity.getVideoId());
						errorLog += "更新数据失败！！id="+entity.getVideoId();
					}
				} catch (IOException e) {
					System.out.println("失败：" + fileName+",id="+urlList.get(i).getVideoId());
				} catch (Exception e) {
					System.out.println("失败：" + fileName+",id="+urlList.get(i).getVideoId());
				}
			}
		}
		System.out.println("错误日志："+errorLog);
	}
	/**
	 * //如果是Windows情况下，localFilePath格式是 D:\\qiniu\\test.png
	 * @param localFilePath
	 * @return
	 */
	public static void uploadFile(String localFilePath,String fileName){
	    //构造一个带指定Zone对象的配置类
	    Configuration cfg = new Configuration(Zone.zone0());
	    //...其他参数参考类注释
	    UploadManager uploadManager = new UploadManager(cfg);
	    //...生成上传凭证，然后准备上传
	    String accessKey = "HqeuYJi7RXkAKA1SIxXXFmtWVE61A5XcAh5_e1hy";
	    String secretKey = "R9G6oRkDSI7Oo1TnnUMP9HYhT6-TBbX0DxiomTVW";
	    String bucket = "xz-web";
	    //默认不指定key的情况下，以文件内容的hash值作为文件名
	    Auth auth = Auth.create(accessKey, secretKey);
	    String upToken = auth.uploadToken(bucket);
	    try {
	        Response response = uploadManager.put(localFilePath, fileName, upToken);
	        //解析上传成功的结果
	        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
	        System.out.println(putRet.key);
	        System.out.println(putRet.hash);
	    } catch (QiniuException ex) {
	    	errorLog += "上传失败："+localFilePath;
	        Response r = ex.response;
	        System.err.println(r.toString());
	        try {
	            System.err.println(r.bodyString());
	        } catch (QiniuException ex2) {
	        }
	    }
	}
	
	/**
	 * url=http://baidumv.9483000.com/video/img/348586f882ab4485bc89b7ca81e2e328
	 * 返回：/video/img/348586f882ab4485bc89b7ca81e2e328.jpg
	 * 
	 * @param url
	 * @return
	 */
	public static String StringSplit(String url) {
		// String url=
		// "http://baidumv.9483000.com/video/img/348586f882ab4485bc89b7ca81e2e328.jpg";
		//  http://cy001.b0.upaiyun.com/comment/img/280e5d2a8c66468aa0e79a1f17092dc6.jpg
		String[] urlStrArray = url.split("/");
		List<String> urlList = new ArrayList<String>();
		for (int i = 0; i < urlStrArray.length; i++) {
			urlList.add(urlStrArray[i]);
		}
		urlList.remove(0);
		urlList.remove(0);
		urlList.remove(0);
		String k = "";
		for (String temp : urlList) {
			k += "/" + temp;
		}
		return k;
	}

	/**
	 * 从网络Url中下载文件
	 * 
	 * @param urlStr
	 * @param fileName
	 * @param savePath
	 * @throws IOException
	 */
	public static void downLoadFromUrl(String urlStr, String fileName, String savePath) throws IOException {
		URL url = new URL(urlStr);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 设置超时间为3秒
		conn.setConnectTimeout(3 * 1000);
		// 防止屏蔽程序抓取而返回403错误
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

		// 得到输入流
		InputStream inputStream = conn.getInputStream();
		// 获取自己数组
		byte[] getData = readInputStream(inputStream);

		// 文件保存位置
		File saveDir = new File(savePath);
		if (!saveDir.exists()) {
			saveDir.mkdir();
		}
		File file = new File(saveDir + File.separator + fileName);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(getData);
		if (fos != null) {
			fos.close();
		}
		if (inputStream != null) {
			inputStream.close();
		}
		System.out.println("info:" + url + " download success");
	}

	/**
	 * 从输入流中获取字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] readInputStream(InputStream inputStream) throws IOException {
		byte[] buffer = new byte[1024];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ((len = inputStream.read(buffer)) != -1) {
			bos.write(buffer, 0, len);
		}
		bos.close();
		return bos.toByteArray();
	}
}

